package com.gitee.zycra.union.api.dao;

import com.gitee.zycra.jdbc.common.BaseDao;
import com.gitee.zycra.jdbc.enums.SQLConditionEnum;
import com.gitee.zycra.jdbc.enums.SQLLinkEnum;
import com.gitee.zycra.jdbc.model.PageQueryWrapper;
import com.gitee.zycra.jdbc.model.PageResult;
import com.gitee.zycra.jdbc.util.SQLBlock;
import com.gitee.zycra.jdbc.util.SQLChain;
import com.gitee.zycra.union.api.common.bo.PageQuery;
import com.gitee.zycra.union.api.common.model.ApiMockTemplate;
import com.gitee.zycra.union.api.common.param.PageQueryMockTemplateParam;
import org.springframework.stereotype.Repository;

/**
 * @author zycra
 */
@Repository
public class ApiMockTemplateDao extends BaseDao<ApiMockTemplate> {

    /**
     * 插入mock模板
     *
     * @param apiMockTemplate 模板对象
     * @return 影响行数
     */
    public int insert(ApiMockTemplate apiMockTemplate) {
        return insertIntoTable(apiMockTemplate);
    }

    /**
     * 根据ID更新
     *
     * @param apiMockTemplate 模板对象
     * @return 影响行数
     */
    public int updateById(ApiMockTemplate apiMockTemplate) {
        return updateTableById(apiMockTemplate);
    }

    /**
     * 根据ID删除
     *
     * @param id 要删除的ID
     * @return 影响行数
     */
    public int updateToDelete(Long id) {
        return updateTableById(new ApiMockTemplate().setId(id).setDeleted(true));
    }

    /**
     * 分页查询
     *
     * @param pageQuery 查询参数
     * @return 查询结果
     */
    public PageResult<ApiMockTemplate> selectMockTemplateForPage(PageQuery<PageQueryMockTemplateParam> pageQuery) {
        PageQueryMockTemplateParam param = pageQuery.getParam();
        SQLChain sqlChain = SQLChain.builder()
                .addBlock(SQLBlock.of(SQLLinkEnum.AND, "group_id", SQLConditionEnum.EQUALS, param.getGroupId()))
                .addBlock(SQLBlock.of(SQLLinkEnum.AND, "template_name", SQLConditionEnum.CONTAINS, param.getTemplateName()))
                .addBlock(SQLBlock.of(SQLLinkEnum.AND, "deleted", SQLConditionEnum.EQUALS, false))
                .build();
        PageQueryWrapper pageQueryWrapper = new PageQueryWrapper(getCountSqlWithOutParam() + sqlChain.getSQL(), sqlChain.getParamList(),
                getSelectAllColumnSql() + sqlChain.getSQL(), sqlChain.getParamList(), pageQuery.getPage(), pageQuery.getSize());
        return selectTableForPage(pageQueryWrapper);
    }
}
